document.addEventListener('DOMContentLoaded', function() {
  const translateBtn = document.getElementById('translateBtn');
  const result = document.getElementById('result');
  const wordDiv = result.querySelector('.word');
  const translationDiv = result.querySelector('.translation');

  translateBtn.addEventListener('click', async function() {
    // 获取当前标签页
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
    // 在当前页面执行脚本获取选中的文本
    const [{result: selectedText}] = await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      function: () => window.getSelection().toString().trim()
    });

    if (!selectedText) {
      translationDiv.textContent = '请先选择要翻译的英文文本';
      result.style.display = 'block';
      return;
    }

    if (!/^[a-zA-Z\s\-']+$/.test(selectedText)) {
      translationDiv.textContent = '请选择英文文本';
      result.style.display = 'block';
      return;
    }

    // 显示正在翻译
    wordDiv.textContent = selectedText;
    translationDiv.textContent = '正在翻译...';
    result.style.display = 'block';

    try {
      // 发送消息给background script进行翻译
      const response = await chrome.runtime.sendMessage({
        type: 'translate',
        text: selectedText
      });

      if (response.success && response.translation) {
        translationDiv.textContent = response.translation;
      } else {
        translationDiv.textContent = '翻译失败: ' + (response.error || '未知错误');
      }
    } catch (error) {
      translationDiv.textContent = '翻译出错: ' + error.message;
    }
  });
}); 